/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package avl.sv.client;

import avl.sv.client.source.StudySourcePort;
import avl.sv.server.training.Training;
import avl.sv.shared.ImageID;
import avl.sv.shared.Permissions;
import avl.sv.shared.SlideReference;
import avl.sv.shared.SlideSet;
import avl.sv.shared.TreeTransferHandler;
import avl.sv.shared.sources.SlideSource;
import avl.sv.shared.sources.StudySource;
import ij.gui.MessageDialog;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.AbstractAction;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DropMode;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

/**
 *
 * @author benbryan
 */
public class StudyManager extends JPanel {

    int cornerMarkerDim = 10;
    MouseActionLogger mouseAction = new MouseActionLogger();
    private Timer updateTimer;
    
    public StudyManager() {
//        setupLookAndFeel();
        initComponents();
        init();
        updateTimer = new Timer(2000, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                StudySource studySource = getSelectedStudySource();
                if (studySource != null) {
                    if (!studySource.isStudyCurrent()) {
                        setSelectedStudy(studySource);
                    }
                }
            }
        });
        updateTimer.setRepeats(true);
        updateTimer.start();
    }  

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled); //To change body of generated methods, choose Tools | Templates.
        for (Component c:getComponents()){
            c.setEnabled(enabled);
        }
    }
       
    public StudySource getSelectedStudySource(){
        return (StudySource) jComboBoxStudy.getSelectedItem();
    }
    
    public void setSelectedStudy(StudySource studySource) {
        if (studySource == null){
            jTreeStudy.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
            jTextAreaStudyDescription.setText("");
            jComboBoxStudy.setSelectedIndex(-1);
        } else {
            studySource.updateSlideSets();
            jTreeStudy.setModel(new DefaultTreeModel(studySource));
            jTextAreaStudyDescription.setText(studySource.getDescription());
        }
    }
            
    long studiesListVersion = 0;
    public void populateStudiesComboBox() {
        Training trainingPort = AdvancedVirtualMicroscope.getTrainingPort();
        if (trainingPort == null){
            return;
        }
        long tempLong  = trainingPort.getStudiesListVersion();
        if (studiesListVersion == tempLong){
            return;
        }
        studiesListVersion = tempLong;
        
        String setRefs = trainingPort.getStudiesList();
        ArrayList<StudyRef> setRefList = new ArrayList<>();
        if (!setRefs.isEmpty()) {
            for (final String pair:setRefs.split(";")){
                final String temp[] = pair.split(",");
                if (temp.length == 2){
                    setRefList.add(new StudyRef(Integer.valueOf(temp[0]), temp[1]));
                }                        
            }
        }
        Collections.sort(setRefList, new Comparator<StudyRef>() {
            @Override
                public int compare(StudyRef s1, StudyRef s2) {
                    return s1.name.compareTo(s2.name);
                }
            }
        );

        ArrayList<StudySource> studies = new ArrayList<>();
        for (StudyRef ref:setRefList){
            StudySourcePort study = new StudySourcePort(trainingPort,  ref.name, ref.id);
            if (study.getVersion() == -1) { //does not exist
                continue;
            }
            studies.add(study);
        }
        StudySource selectedStudy = getSelectedStudySource();       
        jComboBoxStudy.setModel(new DefaultComboBoxModel<>(studies.toArray(new StudySource[studies.size()])));

        //Select the study again if it exists, and exists in the combobox
        jComboBoxStudy.setSelectedIndex(-1);
        if (selectedStudy == null){
            if (jComboBoxStudy.getItemCount() > 0){
                jComboBoxStudy.setSelectedIndex(0);
            } else {
            }
        } else {
            for (int i = 0; i < jComboBoxStudy.getItemCount(); i++){
                if (jComboBoxStudy.getItemAt(i).getId() == selectedStudy.getId()){
                    jComboBoxStudy.setSelectedIndex(i);
                    return;
                }
            }
        }
        if (jComboBoxStudy.getItemCount() > 0){
            jComboBoxStudy.setSelectedIndex(0);
        } else {
            jComboBoxStudy.setSelectedIndex(-1);
        }
    }
    
    public StudySource[] getSlideSources(){
        ComboBoxModel<StudySource> m1 = jComboBoxStudy.getModel();
        StudySource ss[] = new StudySource[m1.getSize()];
        for (int i = 0; i < m1.getSize(); i++){
            ss[i] = m1.getElementAt(i);
        }
        return ss;
    }
    
    private void init() {

        jTreeStudy.setDragEnabled(true);
        jTreeStudy.setDropMode(DropMode.ON_OR_INSERT);
        jTreeStudy.setTransferHandler(TreeTransferHandler.getInstance());
        jTreeStudy.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
        setVisible(true);

    }   
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenuJTreeROIs = new javax.swing.JPopupMenu();
        jMenuItemROIDelete = new javax.swing.JMenuItem();
        jFileChooser1 = new javax.swing.JFileChooser();
        jDialogNewStudy = new javax.swing.JDialog();
        jTextFieldNewStudyName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextAreaNewStudyDescription = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jButtonCreateNewStudy = new javax.swing.JButton();
        jButtonCancelCreateNewStudy = new javax.swing.JButton();
        jPopupMenuSelectedStudy = new javax.swing.JPopupMenu();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTreeStudy = new javax.swing.JTree();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextAreaStudyDescription = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();

        jPopupMenuJTreeROIs.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                jPopupMenuJTreeROIsPopupMenuWillBecomeVisible(evt);
            }
        });

        jMenuItemROIDelete.setText("Delete");
        jMenuItemROIDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemROIDeleteActionPerformed(evt);
            }
        });
        jPopupMenuJTreeROIs.add(jMenuItemROIDelete);

        jDialogNewStudy.setTitle("Create a New Study");
        jDialogNewStudy.setLocationByPlatform(true);

        jTextFieldNewStudyName.setText("default");
        jTextFieldNewStudyName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldNewStudyNameActionPerformed(evt);
            }
        });

        jLabel2.setText("Name");

        jTextAreaNewStudyDescription.setColumns(20);
        jTextAreaNewStudyDescription.setRows(5);
        jScrollPane2.setViewportView(jTextAreaNewStudyDescription);

        jLabel3.setText("Description");

        jButtonCreateNewStudy.setText("Create");
        jButtonCreateNewStudy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCreateNewStudyActionPerformed(evt);
            }
        });

        jButtonCancelCreateNewStudy.setText("Cancel");
        jButtonCancelCreateNewStudy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelCreateNewStudyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jDialogNewStudyLayout = new javax.swing.GroupLayout(jDialogNewStudy.getContentPane());
        jDialogNewStudy.getContentPane().setLayout(jDialogNewStudyLayout);
        jDialogNewStudyLayout.setHorizontalGroup(
            jDialogNewStudyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDialogNewStudyLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jDialogNewStudyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jDialogNewStudyLayout.createSequentialGroup()
                        .addGap(0, 197, Short.MAX_VALUE)
                        .addGroup(jDialogNewStudyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jDialogNewStudyLayout.createSequentialGroup()
                                .addComponent(jTextFieldNewStudyName, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2))
                            .addGroup(jDialogNewStudyLayout.createSequentialGroup()
                                .addComponent(jButtonCreateNewStudy, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonCancelCreateNewStudy, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jScrollPane2)
                    .addGroup(jDialogNewStudyLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jDialogNewStudyLayout.setVerticalGroup(
            jDialogNewStudyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDialogNewStudyLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jDialogNewStudyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldNewStudyName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jDialogNewStudyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonCreateNewStudy)
                    .addComponent(jButtonCancelCreateNewStudy))
                .addGap(26, 26, 26)
                .addComponent(jLabel3)
                .addGap(4, 4, 4)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPopupMenuSelectedStudy.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                jPopupMenuSelectedStudyPopupMenuWillBecomeVisible(evt);
            }
        });

        setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 2, true));

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        jTreeStudy.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTreeStudy.setComponentPopupMenu(jPopupMenuJTreeROIs);
        jTreeStudy.setDragEnabled(true);
        jTreeStudy.setDropMode(javax.swing.DropMode.INSERT);
        jTreeStudy.setEditable(true);
        jTreeStudy.setRootVisible(false);
        jTreeStudy.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTreeStudyMouseClicked(evt);
            }
        });
        jTreeStudy.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTreeStudyValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTreeStudy);

        jTextAreaStudyDescription.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextAreaStudyDescriptionFocusLost(evt);
            }
        });
        jScrollPane3.setViewportView(jTextAreaStudyDescription);

        jLabel5.setText("Description");

        jLabel6.setText("Slides in selected study");

        jComboBoxStudy.setComponentPopupMenu(jPopupMenuSelectedStudy);
        jComboBoxStudy.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                jComboBoxStudyPopupMenuWillBecomeVisible(evt);
            }
        });
        jComboBoxStudy.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBoxStudyItemStateChanged(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Study Manager");

        jLabel7.setText("Selected Study");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addComponent(jScrollPane3)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jComboBoxStudy, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5)
                    .addComponent(jLabel7))
                .addGap(0, 92, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBoxStudy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTreeStudyValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreeStudyValueChanged

    }//GEN-LAST:event_jTreeStudyValueChanged

    private void jPopupMenuJTreeROIsPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jPopupMenuJTreeROIsPopupMenuWillBecomeVisible

    }//GEN-LAST:event_jPopupMenuJTreeROIsPopupMenuWillBecomeVisible

    private void jMenuItemROIDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemROIDeleteActionPerformed
        DefaultTreeModel model = (DefaultTreeModel) jTreeStudy.getModel();
        Object obj = jTreeStudy.getSelectionPath().getLastPathComponent();
        if (obj instanceof SlideReference) {
            SlideReference sr = (SlideReference) obj;
            StudySourcePort ssp = (StudySourcePort) sr.getParent().getParent();
            ssp.clearAnnotations(sr);
            model.removeNodeFromParent(sr);
        }
        if (obj instanceof SlideSet){
            SlideSet ss = (SlideSet) obj;
            for (SlideReference sr:ss.getSlides()){
                StudySourcePort ssp = (StudySourcePort) sr.getParent().getParent();
                ssp.clearAnnotations(sr);
                model.removeNodeFromParent(sr);
            }
            model.removeNodeFromParent(ss);
        }
        
        SlideViewer sv = AdvancedVirtualMicroscope.getSelectedSlideviewer();
        if (sv != null){
            sv.repaint();
        }
        
    }//GEN-LAST:event_jMenuItemROIDeleteActionPerformed

    private void jTextFieldNewStudyNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldNewStudyNameActionPerformed

    }//GEN-LAST:event_jTextFieldNewStudyNameActionPerformed

    private void jButtonCreateNewStudyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCreateNewStudyActionPerformed
        String studyName = jTextFieldNewStudyName.getText();
        String result = AdvancedVirtualMicroscope.getTrainingPort().createStudy( studyName);
        int id = Integer.valueOf(result);
        if (result.startsWith("error:") || (id < 0)) {
            MessageDialog md = new MessageDialog(null, "Error", "A study by that name already exists");
            return;
        }
        StudySourcePort newStudy = new StudySourcePort(AdvancedVirtualMicroscope.getTrainingPort(),  studyName, id);
        newStudy.setDescription(jTextAreaNewStudyDescription.getText());
        jComboBoxStudy.addItem(newStudy);
        jComboBoxStudy.setSelectedItem(newStudy);
        jDialogNewStudy.setVisible(false);
    }//GEN-LAST:event_jButtonCreateNewStudyActionPerformed

    private void jButtonCancelCreateNewStudyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelCreateNewStudyActionPerformed
        jDialogNewStudy.setVisible(false);
    }//GEN-LAST:event_jButtonCancelCreateNewStudyActionPerformed
        
    private void jTreeStudyMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTreeStudyMouseClicked
        if ((evt.getClickCount() == 2) && (evt.getButton() == MouseEvent.BUTTON1)){
            TreePath path = jTreeStudy.getClosestPathForLocation(evt.getPoint().x, evt.getPoint().y);
            if (path == null){ 
                return;
            }
            Object obj = path.getLastPathComponent();
            if (obj instanceof SlideReference){
                // Bring Slideviewer for this set to front
                SlideReference slideReference = (SlideReference) obj;
                ArrayList<SlideViewer> openSvs = AdvancedVirtualMicroscope.getOpenSlideViewers();
                
                // In case SlideViwer is already open
                for (SlideViewer sv:openSvs){
                    if (ImageID.hashesAreEqual(sv.getSlideSource().getHash(), slideReference.hash)){
                        AdvancedVirtualMicroscope.setTopSlideViewer(sv);
                        AdvancedVirtualMicroscope.getInstance().toFront();
                        return;
                    }
                }
                // If not already open, open it
                SlideSource ss = AdvancedVirtualMicroscope.getSlideSource(slideReference);
                AdvancedVirtualMicroscope.addSlideViewer(ss);
                AdvancedVirtualMicroscope.getInstance().toFront();
            } 
        }
    }//GEN-LAST:event_jTreeStudyMouseClicked

    private void jComboBoxStudyPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jComboBoxStudyPopupMenuWillBecomeVisible
        populateStudiesComboBox();
    }//GEN-LAST:event_jComboBoxStudyPopupMenuWillBecomeVisible

    private void jTextAreaStudyDescriptionFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextAreaStudyDescriptionFocusLost
        StudySource studySource = getSelectedStudySource();
        if (studySource == null){
            jTextAreaNewStudyDescription.setText("");
            return;
        }
        studySource.setDescription(jTextAreaStudyDescription.getText());
        jTextAreaNewStudyDescription.setText(studySource.getDescription());
        AdvancedVirtualMicroscope.setStatusText("Description updated", 4*1000);
    }//GEN-LAST:event_jTextAreaStudyDescriptionFocusLost

    private void jPopupMenuSelectedStudyPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jPopupMenuSelectedStudyPopupMenuWillBecomeVisible
        jPopupMenuSelectedStudy.removeAll();
        Object obj = jComboBoxStudy.getSelectedItem();
        if (obj instanceof StudySourcePort){
            final StudySourcePort ssp = (StudySourcePort) obj;
            String ps = AdvancedVirtualMicroscope.getTrainingPort().getPermissionsStudy(ssp.getID(), null);
            Permissions p = Permissions.valueOf(ps);
            if (p.equals(Permissions.ADMIN)){
                JMenuItem itemPermission = new JMenuItem("Permissions");
                itemPermission.addActionListener(new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        new PermissionPrompt(AdvancedVirtualMicroscope.getInstance(),
                                "study", ssp.getID(),
                                AdvancedVirtualMicroscope.getTrainingPort()).setVisible(true);
                    }
                });
                jPopupMenuSelectedStudy.add(itemPermission);

                JMenuItem itemDelete = new JMenuItem("Delete");
                itemDelete.addActionListener(new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String result = ssp.delete();
                        if (result.startsWith("error:")){
                            AdvancedVirtualMicroscope.setStatusText("Could not delete study " + ssp.getName() +". " + result, 4*1000);
                        } else {
                            populateStudiesComboBox();
                            AdvancedVirtualMicroscope.setStatusText("Study " + ssp.getName() + " was deleted", 4*1000);
                        }
                    }
                });
                jPopupMenuSelectedStudy.add(itemDelete);
            }

        }
        JMenuItem itemNew = new JMenuItem("Create new");
        itemNew.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jDialogNewStudy.setVisible(true);
                jDialogNewStudy.setSize(jDialogNewStudy.getPreferredSize());
            }
        });
        jPopupMenuSelectedStudy.add(itemNew);        
        jPopupMenuSelectedStudy.pack();
    }//GEN-LAST:event_jPopupMenuSelectedStudyPopupMenuWillBecomeVisible

    private void jComboBoxStudyItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxStudyItemStateChanged
        switch (evt.getStateChange()){
            case ItemEvent.SELECTED:
                setSelectedStudy(getSelectedStudySource());
                break;
        }
    }//GEN-LAST:event_jComboBoxStudyItemStateChanged
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancelCreateNewStudy;
    private javax.swing.JButton jButtonCreateNewStudy;
    private static final javax.swing.JComboBox<StudySource> jComboBoxStudy = new javax.swing.JComboBox<StudySource>();
    private javax.swing.JDialog jDialogNewStudy;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JMenuItem jMenuItemROIDelete;
    private javax.swing.JPopupMenu jPopupMenuJTreeROIs;
    private javax.swing.JPopupMenu jPopupMenuSelectedStudy;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextAreaNewStudyDescription;
    private javax.swing.JTextArea jTextAreaStudyDescription;
    private javax.swing.JTextField jTextFieldNewStudyName;
    private javax.swing.JTree jTreeStudy;
    // End of variables declaration//GEN-END:variables

    ComboBoxModel<StudySource> getStudiesComboBoxModel() {
        return jComboBoxStudy.getModel();
    }
    

   
}


